package models

import (
	"fmt"
	//"time"

	"github.com/jinzhu/gorm"
)

type PerformanceConfig struct {
	gorm.Model
	InterfaceName              string         `gorm:"column:interfacename;primary_key;unique"`
	TestId					string         `gorm:"column:testid"`
	MaxUsers                  string         `gorm:"column:maxusers"`
	AvgThroughput                 string         `gorm:"column:avgthroughput"`	
	Errors                    string		 `gorm:"column:errors"`
	AvgResponseTime              string        `gorm:"column:avgResponsetime"`
	ResponseTime90              string         `gorm:"column:responsetime90"`
	AvgBandwidth              string         `gorm:"column:avgbandwidth"`
	AvgTransactions             string         `gorm:"column:avgtransactions"`
    
}

func (PerformanceConfig) TableName() string {
	return "performance_config"
}

func (*PerformanceConfig) Create(config PerformanceConfig) {	
	plan := PerformanceConfig{}
	InterfaceName := config.InterfaceName	
	err := db.Where("interfacename=?",InterfaceName).First(&plan).Error
	if err != nil {
		// error handling...
		fmt.Println(err)
		if gorm.IsRecordNotFoundError(err){
			db.Create(&config)  // newUser not user
		}
	}else{
		db.Model(&config).Where("interfacename = ?", InterfaceName).Updates(&config)
	}	
}


func (*PerformanceConfig) Update(InterfaceName string, plan PerformanceConfig) {
	//fmt.Printf("修改%v的状态", plan)
	plannew := PerformanceConfig{}
	db.Model(&plannew).Where("interfacename=?",InterfaceName).Updates(&plan)
}




func (*PerformanceConfig) Get(InterfaceName string) PerformanceConfig {
	plan := PerformanceConfig{}
	//fmt.Println("开始查找:", planid)
	db.Where("interfacename=?",InterfaceName).First(&plan)	
	//fmt.Printf("plan:%+v", plan)
	return plan
}

func (*PerformanceConfig) GetList() []PerformanceConfig {
	plans := []PerformanceConfig{}
	db.Limit(20).Find(&plans)
	fmt.Printf("plan:%+v", plans)
	return plans

}

func (*PerformanceConfig) Delete(PlanID string) {
	plan := PerformanceConfig{}
	fmt.Println("delete recode:", PlanID)
	db.Where("planid=?",PlanID).Delete(plan)	
}

func (*PerformanceConfig)GetExectTime(planid string) float64 {
	plan := PerformanceConfig{}
	//fmt.Println("开始查找:", planid)
	db.Where("planid=?",planid).First(&plan)
	starttime := plan.CreatedAt
	endtime := plan.UpdatedAt
	execttime := endtime.Sub(starttime).Seconds()	
	return execttime
}